import React, { useEffect, useState } from 'react';
import {
  AutoComplete,
  Button,
  Divider,
  Input,
  List,
  message,
  Select,
  Space,
  Typography,
} from 'antd';
import {
  LightFilter,
  PageContainer,
  ProFormSelect,
} from '@ant-design/pro-components';
import './index.less';
import { useModel } from '@umijs/max';
import { TeamType } from '@/models/team';
import { listOpenTeam } from '@/services/teamService';
import { Tag } from 'antd/es';
import ApplyJoinTeam from '@/pages/index/components/ApplyJoinTeam';
import { listSuggestWordsSearch } from '@/services/searchWordsService';
import { SearchWordsType } from '@/models/searchWords';

// 默认分页大小
const DEFAULT_PAGE_SIZE = 10;

/**
 * 主页
 */

const IndexPage: React.FC = () => {
  const [teamList, setTeamList] = useState<TeamType.TeamVo[]>([]);
  const [total, setTotal] = useState<number>(0);
  const { initialState } = useModel('@@initialState');
  const tagMap = initialState?.tagMap || {};
  const [options, setOptions] = useState<{ value: string; label: string }[]>(
    [],
  );
  const [JoinModalVisible, setJoinModalVisible] = useState<boolean>(false);
  const [JoinData, setJoinData] = useState<TeamType.TeamVo>();
  const loginUser = initialState?.loginUser;
  const [loading, setLoading] = useState<boolean>(true);
  const [searchWords, setSearchWords] =
    useState<SearchWordsType.SuggestWordsSearchVo[]>();

  const initSearchParams: TeamType.TeamListQueryRequest = {
    current: 1,
    pageSize: DEFAULT_PAGE_SIZE,
    // 只展示已审核通过的
    teamApplyState: 1,
    sortField: 'createTime',
    sortOrder: 'descend', // ascend descend
  };
  const [searchParams, setSearchParams] =
    useState<TeamType.TeamListQueryRequest>(initSearchParams);

  const handleSearch = () => {
    const res = searchWords
      ?.map((item) => item['searchInformation'])
      ?.map((domain, index) => ({
        value: domain,
        label: index + ':' + domain,
      }));

    // @ts-ignore
    setOptions(res);
  };

  const JoinVisble = (teamVo: TeamType.TeamVo) => {
    if (!teamVo) {
      return [];
    }
    setJoinData(teamVo);
    setJoinModalVisible(true);
  };

  const sortSelect = (
    <Select
      size="large"
      placeholder="排序"
      defaultValue="createTime"
      onChange={(value: string) => {
        setSearchParams({ ...searchParams, sortField: value });
      }}
    >
      <Select.Option value="createTime">最新</Select.Option>
      <Select.Option value="id">默认</Select.Option>
    </Select>
  );

  /**
   * 加载数据
   */
  // 加载数据
  useEffect(() => {
    setLoading(true);
    listOpenTeam(searchParams)
      .then((res) => {
        // @ts-ignore
        setTeamList(res.data.records);
        // @ts-ignore
        setTotal(res.data.total);
      })
      .catch((e) => {
        message.error('加载失败，' + e.message);
      })
      .finally(() => setLoading(false));
    listSuggestWordsSearch().then((res) => {
      setSearchWords(res.data.records);
    });
  }, [searchParams]);

  /**
   * 根据分类获取标签选项数组
   * @param category
   */
  const getOptions = (category: string) => {
    if (!category || !tagMap[category]) {
      return [];
    }
    return tagMap[category].map((tag) => {
      return {
        value: tag.tagName,
        label: tag.tagName,
      };
    });
  };

  return (
    <div id="indexPage">
      <div className="banner">
        <Space direction="vertical" size="large" className="search-wrapper">
          <Typography.Title level={2} className="title">
            找寻一起开发的伙伴
          </Typography.Title>

          <AutoComplete
            dropdownMatchSelectWidth={500}
            style={{ width: 600 }}
            onFocus={handleSearch}
            options={[
              {
                label: '热搜',
                options: options,
              },
            ]}
          >
            <Input.Search
              size="large"
              placeholder="你想找寻怎么有项目开发？"
              allowClear
              // todo 搜索
              onSearch={(value) => {
                setSearchParams({
                  ...searchParams,
                  ...initSearchParams,
                  teamDescription: value,
                });
              }}
            ></Input.Search>
          </AutoComplete>
          {/*<AutoComplete*/}
          {/*    popupClassName="certain-category-search-dropdown"*/}
          {/*    dropdownMatchSelectWidth={500}*/}
          {/*    style={{ width: 250 }}*/}
          {/*    options={options}*/}
          {/*>*/}
          {/*  <Input.Search size="large" placeholder="input here" />*/}
          {/*</AutoComplete>*/}
          <LightFilter
            bordered
            onFinish={async (values) => {
              setSearchParams({
                teamDescription: searchParams.teamDescription,
                ...initSearchParams,
                ...values,
              });
            }}
          >
            <ProFormSelect
              options={getOptions('project')}
              name="teamType"
              label="项目"
              required
              showSearch
            />
            {/*todo 传递值为数组需要进行 JSON转换，但是组件内置 */}
            {/*<ProFormSelect*/}
            {/*    options={getOptions('technology')}*/}
            {/*    name="teamTechnologyType"*/}
            {/*    label="技术"*/}
            {/*    required*/}
            {/*    fieldProps={{*/}
            {/*        mode:'multiple'*/}
            {/*    }}*/}
            {/*    showSearch*/}
            {/*/>*/}
          </LightFilter>
        </Space>
      </div>
      <PageContainer
        title={`队伍数量（${total}）`}
        className="post-list-wrapper"
        extra={sortSelect}
      >
        <List
          itemLayout="vertical"
          size="large"
          loading={loading}
          pagination={{
            total,
            onChange: (current) => {
              setSearchParams({ ...searchParams, current });
              window.scrollTo({
                top: 0,
              });
            },
            pageSize: DEFAULT_PAGE_SIZE,
          }}
          dataSource={teamList}
          renderItem={(teamVo, index) => (
            <List.Item
              key={index}
              extra={
                <img
                  height={240}
                  src={
                    teamVo?.teamAvatarUrl ||
                    'https://xingqiu-tuchuang-1256524210.cos.ap-shanghai.myqcloud.com/9226/logo/nothingImg.jpg'
                  }
                />
              }
            >
              <Space direction="vertical">
                <div style={{ marginBottom: '1em' }}>
                  队伍名称:<Tag>{teamVo.teamName}</Tag>
                  <br />
                  项目已有人数/最多人数:
                  <Tag>
                    {teamVo.minNum}/{teamVo.maxNum}
                  </Tag>
                  <br />
                  类型：<Tag>{teamVo.teamType}</Tag>
                  <br />
                  技术：<Tag>{teamVo.teamTechnologyType}</Tag>
                </div>
                <Typography.Paragraph
                  ellipsis={{ rows: 7, expandable: true, symbol: '展开' }}
                >
                  简介:{teamVo.teamDescription}
                </Typography.Paragraph>
                <Space
                  split={<Divider type="vertical" />}
                  style={{ fontSize: 14 }}
                >
                  <Typography.Text type="secondary">
                    {
                      // @ts-ignore
                      teamVo.createTime.toString().split('T')[0]
                    }
                  </Typography.Text>
                  <Button
                    style={{
                      display:
                        teamVo.apply === 2 && teamVo.userId !== loginUser?.id
                          ? 'block'
                          : 'none',
                    }}
                    type="primary"
                    onClick={() => JoinVisble(teamVo)}
                  >
                    加入申请队伍
                  </Button>
                  <Button
                    style={{
                      display:
                        teamVo.apply === 1 || teamVo.userId === loginUser?.id
                          ? 'block'
                          : 'none',
                    }}
                    type="primary"
                    disabled
                  >
                    已加入
                  </Button>
                  <Button
                    style={{ display: teamVo.apply === 0 ? 'block' : 'none' }}
                    danger
                    disabled
                  >
                    申请中
                  </Button>
                  {/*<Button type="text" onClick={() => doThumb(post)}>*/}
                  {/*    <Space>*/}
                  {/*        {post.hasThumb ? <LikeFilled /> : <LikeOutlined />}*/}
                  {/*        {post.thumbNum}*/}
                  {/*    </Space>*/}
                  {/*</Button>*/}
                  {/*<Button*/}
                  {/*    type="text"*/}
                  {/*    onClick={() => {*/}
                  {/*        setReportedId(post.id);*/}
                  {/*        setReportModalVisible(true);*/}
                  {/*    }}*/}
                  {/*>*/}
                  {/*    反馈*/}
                  {/*</Button>*/}
                </Space>
              </Space>
            </List.Item>
          )}
        />
        <ApplyJoinTeam
          // @ts-ignore
          oldData={JoinData}
          modalVisible={JoinModalVisible}
          onSubmit={() => {}}
          onCancel={() => {
            setJoinModalVisible(false);
          }}
          // @ts-ignore
          loginUser={loginUser}
        />
      </PageContainer>
    </div>
  );
};

export default IndexPage;
